// 获取DOM元素
const dropAreas = document.querySelectorAll('.drop-area');
const fileInputs = document.querySelectorAll('.file-input');
const browseButtons = document.querySelectorAll('.browse-btn');
const stitchBtn = document.getElementById('stitch-btn');
const resetBtn = document.getElementById('reset-btn');
const resultContainer = document.getElementById('result-container');
const resultImage = document.getElementById('result-image');
const downloadBtn = document.getElementById('download-btn');
const loadingOverlay = document.getElementById('loading-overlay');
const notification = document.getElementById('notification');
const notificationMessage = document.getElementById('notification-message');

// 存储上传的图片数据
let uploadedImages = [null, null];

// 添加算法选择下拉菜单
const mainContent = document.querySelector('.main-content');
const algorithmSelector = document.createElement('div');
algorithmSelector.className = 'algorithm-selector';
algorithmSelector.innerHTML = `
    <label for="algorithm">选择拼接算法:</label>
    <select id="algorithm" class="algorithm-select">
        <option value="tradition">传统算法</option>
        <option value="udis2">UDIS2算法 (高级)</option>
    </select>
`;

// 在action-buttons之前插入算法选择器
const actionButtons = document.querySelector('.action-buttons');
mainContent.insertBefore(algorithmSelector, actionButtons);

// 获取算法选择器元素
const algorithmSelect = document.getElementById('algorithm');

// 监听算法选择变化
algorithmSelect.addEventListener('change', function() {
    // 通知后端算法选择已更改
    window.pywebview.api.set_algorithm(this.value);
});

// 拖放功能
dropAreas.forEach((dropArea, index) => {
    // 阻止默认拖放行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    // 高亮拖放区域
    ['dragenter', 'dragover'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            dropArea.classList.add('highlight');
        });
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropArea.addEventListener(eventName, () => {
            dropArea.classList.remove('highlight');
        });
    });

    // 处理拖放文件
    dropArea.addEventListener('drop', (e) => {
        const file = e.dataTransfer.files[0];
        if (file && file.type.match('image.*')) {
            handleFile(file, index);
        }
    });

    // 点击浏览按钮
    const browseBtn = dropArea.querySelector('.browse-btn');
    const fileInput = dropArea.querySelector('.file-input');

    browseBtn.addEventListener('click', () => {
        fileInput.click();
    });

    // 处理文件选择
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length) {
            handleFile(e.target.files[0], index);
        }
    });
});

// 处理文件上传
function handleFile(file, index) {
    const reader = new FileReader();
    const dropArea = dropAreas[index];
    const previewImage = dropArea.querySelector('.preview-image');

    reader.onload = (e) => {
        // 显示预览图
        previewImage.src = e.target.result;
        dropArea.classList.add('has-image');

        // 存储图片数据
        uploadedImages[index] = e.target.result;

        // 检查是否可以启用拼接按钮
        if (uploadedImages[0] && uploadedImages[1]) {
            stitchBtn.removeAttribute('disabled');
        }
    };

    reader.readAsDataURL(file);
}

// 拼接按钮点击事件
stitchBtn.addEventListener('click', function() {
    if (uploadedImages[0] && uploadedImages[1]) {
        // 显示加载动画
        loadingOverlay.classList.add('show');
        stitchBtn.classList.add('processing');
        stitchBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg> 处理中...';
        
        // 将图片数据发送到后端
        Promise.all([
            window.pywebview.api.upload_image(uploadedImages[0], 1),
            window.pywebview.api.upload_image(uploadedImages[1], 2)
        ]).then(() => {
            // 调用后端拼接函数
            return window.pywebview.api.stitch();
        }).then(response => {
            if (response.success) {
                if (response.steps && algorithmSelect.value === 'udis2') {
                    // 显示UDIS2算法结果和中间步骤
                    resultImage.src = response.image;
                    resultContainer.classList.add('show');

                    // 创建中间步骤容器
                    const stepsContainer = document.createElement('div');
                    stepsContainer.className = 'udis2-steps-container';
                    stepsContainer.innerHTML = '<h3>UDIS2处理步骤</h3>';

                    // 创建步骤网格
                    const stepsGrid = document.createElement('div');
                    stepsGrid.className = 'udis2-steps-grid';

                    // 添加每个步骤
                    response.steps.forEach(step => {
                        const stepItem = document.createElement('div');
                        stepItem.className = 'udis2-step-item';
                        stepItem.innerHTML = `
                            <h4>${step.name}</h4>
                            <img src="${step.image}" alt="${step.name}">
                        `;
                        stepsGrid.appendChild(stepItem);
                    });

                    stepsContainer.appendChild(stepsGrid);

                    // 添加性能信息 - REMOVED from here

                    // 检查是否已存在步骤容器，如果存在则移除
                    const existingStepsContainer = document.querySelector('.udis2-steps-container');
                    if (existingStepsContainer) {
                        existingStepsContainer.remove();
                    }

                    // 将步骤容器添加到结果容器之后
                    resultContainer.parentNode.insertBefore(stepsContainer, resultContainer.nextSibling);

                    loadingOverlay.classList.remove('show');
                    stitchBtn.classList.remove('processing');
                    stitchBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 3H3C1.9 3 1 3.9 1 5v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zm-10-7h9v6h-9z"/></svg> 开始拼接';
                    showNotification('UDIS2图像拼接成功！', 'success');
                    // 显示拼接时间通知
                    if (response.performance && response.performance.execution_time !== undefined) {
                        const timeInSeconds = response.performance.execution_time.toFixed(2);
                        showNotification(`UDIS2 算法拼接耗时: ${timeInSeconds} 秒`, 'success'); // Use 'success' type
                    }

                    // 滚动到结果区域
                    resultContainer.scrollIntoView({ behavior: 'smooth' });

                    // 更新下载按钮
                    downloadBtn.onclick = function() {
                        window.pywebview.api.save_result();
                    };
                } else {
                    // 显示传统算法结果
                    resultImage.src = response.image;
                    resultContainer.classList.add('show');
                    loadingOverlay.classList.remove('show');
                    stitchBtn.classList.remove('processing');
                    stitchBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 3H3C1.9 3 1 3.9 1 5v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zm-10-7h9v6h-9z"/></svg> 开始拼接';
                    showNotification('图像拼接成功！', 'success');
                    // 显示拼接时间通知
                    if (response.performance && response.performance.execution_time !== undefined) {
                        const timeInSeconds = response.performance.execution_time.toFixed(2);
                        showNotification(`传统算法拼接耗时: ${timeInSeconds} 秒`, 'success'); // Use 'success' type
                    }

                    // 滚动到结果区域
                    resultContainer.scrollIntoView({ behavior: 'smooth' });

                    // 更新下载按钮
                    downloadBtn.onclick = function() {
                        window.pywebview.api.save_result();
                    };

                    // 清除旧的性能信息（如果有）
                    const existingPerfInfo = resultContainer.querySelector('.performance-info');
                    if (existingPerfInfo) {
                        existingPerfInfo.remove();
                    }
                    // NOTE: Inline performance info display removed as per original (failed) replace block's intent
                }
            } else {
                loadingOverlay.classList.remove('show');
                stitchBtn.classList.remove('processing');
                stitchBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 3H3C1.9 3 1 3.9 1 5v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zm-10-7h9v6h-9z"/></svg> 开始拼接';
                showNotification(response.message, 'error');
            }
        }).catch(error => {
            loadingOverlay.classList.remove('show');
            stitchBtn.classList.remove('processing');
            stitchBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M21 3H3C1.9 3 1 3.9 1 5v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zm-10-7h9v6h-9z"/></svg> 开始拼接';
            showNotification('处理过程中出错: ' + error, 'error');
        });
    }
});

// 重置按钮点击事件
resetBtn.addEventListener('click', function() {
    // 调用后端重置函数
    window.pywebview.api.reset().then(response => {
        if (response.success) {
            // 清空上传的图片数据
            uploadedImages = [null, null];

            // 重置拖放区域
            dropAreas.forEach(dropArea => {
                const previewImage = dropArea.querySelector('.preview-image');
                previewImage.src = '#';
                dropArea.classList.remove('has-image');
            });

            // 隐藏结果区域
            resultContainer.classList.remove('show');
            resultImage.src = '#'; // 清空结果图片

            // 移除UDIS2中间步骤容器（如果存在）
            const existingStepsContainer = document.querySelector('.udis2-steps-container');
            if (existingStepsContainer) {
                existingStepsContainer.remove();
            }

            // 禁用拼接按钮
            stitchBtn.setAttribute('disabled', true);

            // 重置算法选择为默认值（可选，根据需求）
            // algorithmSelect.value = 'tradition';

            showNotification('已重置', 'info');
        } else {
            showNotification(`重置失败: ${response.message}`, 'error');
        }
    }).catch(error => {
        console.error('重置时出错:', error);
        showNotification('重置过程中发生错误', 'error');
    });
});

// 显示通知
function showNotification(message, type) {
    const successIcon = notification.querySelector('.success-icon');
    const errorIcon = notification.querySelector('.error-icon');
    
    notificationMessage.textContent = message;
    
    if (type === 'success') {
        successIcon.style.display = 'block';
        errorIcon.style.display = 'none';
        notification.className = 'notification success show';
    } else {
        successIcon.style.display = 'none';
        errorIcon.style.display = 'block';
        notification.className = 'notification error show';
    }
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}